package com.ruoyi.zhike.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteDeptService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysDept;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.zhike.db.domain.MerchantBaseInfo;
import com.ruoyi.zhike.merchant.constant.MerchantConstant;
import com.ruoyi.zhike.merchant.service.IMerchantBaseInfoService;
import com.ruoyi.zhike.service.IMerchantCommonService;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class MerchantCommonServiceImpl implements IMerchantCommonService {

    @Autowired
    RemoteDeptService remoteDeptService;
    @Autowired
    RemoteUserService remoteUserService;
    @Autowired
    IMerchantBaseInfoService merchantBaseInfoService;

    @Override
    public AjaxResult insertMerchantBaseInfo(MerchantBaseInfo merchantBaseInfo) {

        SysDept sysDept = new SysDept();
        sysDept.setParentId(MerchantConstant.MERCHANT_PARENT_DEPT_ID);
        sysDept.setDeptName(merchantBaseInfo.getInfoName());
        sysDept.setOrderNum(RandomUtils.nextInt(0, 1000));

        AjaxResult ajaxResult= remoteDeptService.registerDeptInfo(sysDept, SecurityConstants.INNER);
        if (ajaxResult.isError()){
            return AjaxResult.error("创建部门信息失败");
        }
        // 部门ID
        Long deptId = Long.valueOf((Integer)ajaxResult.get("data"));

        String loginName = RandomUtil.randomNumbers(9);
        String loginPwd = RandomUtil.randomString(6);
        merchantBaseInfo.setAdminName(loginName);
        merchantBaseInfo.setAdminPwd(loginPwd);
        merchantBaseInfo.setDeptId(deptId);
        //
        SysUser sysUser = new SysUser();
        sysUser.setNickName(merchantBaseInfo.getInfoName());
        sysUser.setUserName(merchantBaseInfo.getAdminName());
        //密码加密
        String passward = SecurityUtils.encryptPassword(merchantBaseInfo.getAdminPwd());
        sysUser.setPassword(passward);

        sysUser.setNickName(merchantBaseInfo.getInfoName());
        sysUser.setDeptId(deptId);
        sysUser.setRoleIds(new Long[]{MerchantConstant.MERCHANT_ROLEID_MANAGER});

        R<Long> userResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);
        System.out.println(JSON.toJSONString(userResult));
        if (R.FAIL == userResult.getCode()){
            return AjaxResult.error("创建用户信息失败");
        }

        merchantBaseInfo.setAdminId(userResult.getData());
        int i = merchantBaseInfoService.insertMerchantBaseInfo(merchantBaseInfo);

        return i>0?AjaxResult.success():AjaxResult.error();
    }
}
